import { injectable, inject } from 'tsyringe';
import { WebSocketManagerToken } from '../../domain/interfaces/IWebSocketManager';
import type { IWebSocketManager, CustomWebSocket } from '../../domain/interfaces/IWebSocketManager';
import { ServerMessage } from '../../domain/types';
import { LoggerToken } from '../../domain/interfaces/ILogger';
import type { ILogger } from '../../domain/interfaces/ILogger';

@injectable()
export class WebSocketManager implements IWebSocketManager {
  private connections: Map<string, CustomWebSocket> = new Map();

  constructor(@inject(LoggerToken) private logger: ILogger) {}

  addConnection(ws: CustomWebSocket, user: any): void {
    ws.user = user;
    this.connections.set(user.userId, ws);
    this.logger.info('Connection registered in manager', { userId: user.userId });
  }

  removeConnection(userId: string): void {
    this.connections.delete(userId);
    this.logger.info('Connection removed from manager', { userId });
  }

  broadcastToRoom(roomId: string, message: ServerMessage): void {
    // 简化：广播到所有连接（真实实现应根据 roomId 筛选）
    for (const ws of this.connections.values()) {
      if (ws.readyState === 1) ws.send(JSON.stringify(message));
    }
  }

  sendToUser(userId: string, message: ServerMessage): void {
    const ws = this.connections.get(userId);
    if (ws && ws.readyState === 1) ws.send(JSON.stringify(message));
  }

  getConnection(userId: string): CustomWebSocket | undefined {
    return this.connections.get(userId);
  }
}
